package com.wang.hello;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.net.InetSocketAddress;

/**
 * @Author 97089
 * @Date 2022/1/4 11:02
 * @Version 1.0
 */
public class AppServerHello {

    private final int port;

    public AppServerHello(int port) {
        this.port = port;
    }

    public void run() throws InterruptedException {
        EventLoopGroup loopGroup = new NioEventLoopGroup();

        try{
            ServerBootstrap bootstrap = new ServerBootstrap();

            bootstrap.group(loopGroup)
                    .channel(NioServerSocketChannel.class)
                    .localAddress(new InetSocketAddress(port))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new HandlerServerHello());
                        }
                    });

            ChannelFuture future = bootstrap.bind().sync();
            System.out.println("在"+future.channel().localAddress()+"上开启监听");


            //阻塞操作，closeFuture() 开启了一个channel的监听器
            future.channel().closeFuture().sync();
        }finally {
            loopGroup.shutdownGracefully().sync();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new AppServerHello(8081).run();
    }
}
